package de.web;

import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import de.preisrobot.entity.AmazonArtikelImage;
import de.preisrobot.persistence.dao.ArtikelDao;

public class ImageServlet extends HttpServlet
{

   /**
    * 
    */
   private static final long serialVersionUID = 1L;

   public void init(ServletConfig config) throws ServletException
   {
      super.init(config);

      try
      {
//         WebApplicationContext applicationContext = WebApplicationContextUtils
//            .getWebApplicationContext(getServletContext());
//         ImageGrabberService service = (ImageGrabberService) applicationContext.getBean("imageGrabberService");
//         ImageScheduler.getInstance().setImageService(service);
      }
      catch (Exception es)
      {
         es.printStackTrace();
      }
   }

   public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
   {

      String img = request.getParameter("img");
      String contextPath = request.getContextPath();
      System.out.println(contextPath);

      if (img == null)
         return;

      ServletContext context = getServletContext();

      WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(context);

      ArtikelDao dao = (ArtikelDao) applicationContext.getBean("ArtikelDao");
      AmazonArtikelImage image = dao.getImageByArtikelId(Long.parseLong(img));

      if(null == image)
    	  return;
      
      ServletOutputStream out = response.getOutputStream();
      // Use "out" to send content to browser

      response.setContentType("image/"+image.getTyp());
      out.write(image.getImage());
      out.flush();
      out.close();
   }

}
